package org.byqh.dqeai.controller;

import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.byqh.dqeai.common.Json;
import org.byqh.dqeai.dto.EaiModuleSysRoleDTO;
import org.byqh.dqeai.dto.EaiSysRoleModuleDTO;
import org.byqh.dqeai.entity.EaiSysRoleModule;
import org.byqh.dqeai.entity.EaiSysUserRole;
import org.byqh.dqeai.entity.proxy.EaiSysRoleModuleProxy;
import org.byqh.dqeai.enums.SystemEnum;
import org.springframework.web.bind.annotation.*;

import java.util.LinkedList;
import java.util.List;
import java.util.StringJoiner;

@RestController
@RequestMapping("/sysrolem")
@Tag(name = "系统[EaiSysRoleModule] - 角色模块管理")
public class EaiSysRoleModuleController extends BaseController<EaiSysRoleModule, EaiSysRoleModuleProxy> {
    /**
     * 获取某一个具体对象信息
     */
    @GetMapping(value = "/{appId}/{roleId}")
    public Json<List<EaiSysRoleModuleDTO>> get(@PathVariable String appId, @PathVariable String roleId) {
        return this.listImpl(EaiSysRoleModuleDTO.class, query -> {
            return query.where(r -> r.roleId().eq(roleId));
        });
    }

    /**
     * 获取某一个具体对象信息
     */
    @GetMapping(value = "/{userId}")
    public Json<List<EaiSysRoleModuleDTO>> getByUserId(@PathVariable String userId) {
        return this.listImpl(EaiSysRoleModuleDTO.class, query -> {
            var subquery = easyEntityQuery.queryable(EaiSysUserRole.class)
                    .where(e -> e.userId().eq(userId))
                    .select(e -> e.roleId());

            return query.where(r -> r.roleId().in(subquery));
        });
    }

    /**
     * 查询全部对象信息列表
     */
    @PostMapping(value = "/deleteAndInsert")
    public Json<Boolean> deleteAndInsert(
            @RequestBody(required = false) EaiSysRoleModuleDTO dto
    ) {
        // 1.参数验证
        if (dto == null || StringUtils.isBlank(dto.getRoleId())) {
            return Json.errorT(SystemEnum.USER_OPREATION_ENUM.PARAMS_NULL.getValue());
        }

        // 2.删除
        this.getEntityDeletable()
                .where(r -> r.roleId().eq(dto.getRoleId()))
                .executeRows();

        // 3.新增
        if (dto.getModuleIdList() != null && !dto.getModuleIdList().isEmpty()) {
            StringJoiner sj = new StringJoiner(",");

            for (String moduleId : dto.getModuleIdList()) {
                sj.add("'" + moduleId + "'");
            }

            String sql = String.format("""
                     insert into eai_sys_role_module
                                (role_id, app_id, module_id)
                            select '%s', app_id, module_id
                                 from SYS_APP_MODULE where module_id in (%s)
                    """, dto.getRoleId(), sj);

            this.easyQueryClient.sqlExecute(sql);
        }

        return Json.success();
    }

    /**
     * 查询全部对象信息列表
     */
    @PostMapping(value = "/deleteAndInsertByModuleId")
    public Json<Boolean> deleteAndInsertByModuleId(
            @RequestBody(required = false) EaiModuleSysRoleDTO dto
    ) {
        // 1.参数验证
        if (dto == null || StringUtils.isBlank(dto.getAppId()) || StringUtils.isBlank(dto.getModuleId())) {
            return Json.errorT(SystemEnum.USER_OPREATION_ENUM.PARAMS_NULL.getValue());
        }

        // 2.删除
        this.getEntityDeletable()
                .where(e -> e.moduleId().eq(dto.getModuleId()))
                .where(e -> e.appId().eq(dto.getAppId()))
                .executeRows();

        // 3.新增
        var list = new LinkedList<EaiSysRoleModule>();
        for (String roleId : dto.getRoleIdList()) {
            EaiSysRoleModule entity = new EaiSysRoleModule();
            entity.setAppId(dto.getAppId());
            entity.setRoleId(roleId);
            entity.setModuleId(dto.getModuleId());

            list.add(entity);
        }
        this.saveBatch(list);

        return Json.success();
    }
}